import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;


public class SocketThread extends Thread{

	private Socket client;

	public SocketThread(Socket accept) {
		this.client = accept;
	}
	
	public void run() {
		try {
			ObjectInputStream ois = new ObjectInputStream(client
					.getInputStream());
			Student data = (Student) ois.readObject();
			try {
				writeToDB(data);
			} catch (Exception e) {
				e.printStackTrace();
			}

			PrintWriter out = new PrintWriter(client.getOutputStream(), true);
			out.println("Information received successfully");
			out.close();
			ois.close();
			client.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	private void writeToDB(Student data) throws Exception {
		String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
        String url = "jdbc:odbc:Database1";
        String username = "";
        String password = "";
        try {
			Class.forName(driver);
			try {
				System.out.println("a");
				Connection conn = DriverManager.getConnection(url, username, password);
				System.out.println("b");
				PreparedStatement st = conn.prepareStatement("INSERT INTO Student VALUES(?,?,?,?)");
	            st.setString(1, Long.toString(data.getNo()));
	            st.setString(2, data.getName());
	            st.setString(3, data.getSurname());
	            st.setString(4, data.getCourses());
	            st.executeUpdate();

	            st.close();
	            conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
        
		
	}
}
